package java44th.group.controller.wx.storage;

import java44th.group.bean.admin.vo.BaseRespVo;
import java44th.group.bean.po.MarketStorage;
import java44th.group.service.admin.storage.StoreageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * @ProjectName project-second
 * @Descriptiom TODO
 * @Aurhor: 蔡文强
 * @Since: 2022/10/15 21:07
 */
@RestController
@RequestMapping("wx/storage")
public class UploadController {

    @Autowired
    HttpServletRequest request;

    @Autowired
    StoreageService storeageService;

    @RequestMapping(value = "upload", method = RequestMethod.POST)
    public BaseRespVo createFile(MultipartFile file) throws IOException {
        //使用文件上传组件有要求，必须表单中含有Multipart/form-data才可以使用commons-fileupload组件
        // boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        // if(!isMultipart){
        //     //没有包含上传的文件
        //     return BaseRespVo.invalidParameter("请求参数不正确");
        // }

        long size = file.getSize();
        if (size > 1024 * 1024) {
            return BaseRespVo.invalidParameter("文件太大了");
        }
        if (file.getOriginalFilename().length()>200){
            return BaseRespVo.invalidParameter("文件名称过长,请重新上传");
        }

        String originalFilename = file.getOriginalFilename();
        if (!originalFilename.endsWith("g")) {
            return BaseRespVo.invalidParameter("必须是jpg类型");
        }

        UUID uuid = UUID.randomUUID();

        originalFilename = uuid + "-" + originalFilename;
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
        String resourcesPath = applicationHome.getDir().getParentFile()
                .getParentFile().getAbsolutePath()
                + "\\target\\classes\\static\\img";
        String finalPath = resourcesPath + "\\" + originalFilename;
        // 保存目录位置根据项目需求可随意更改
        //D:\CodeJava\other\springboot-all\project-second\src\main\resources\static\img获取到是这个
//        System.out.println(applicationHome.getDir().getParentFile()
//                .getParentFile().getAbsolutePath() + "\\src\\main\\resources\\static\\img");

        //获取到是这个D:/CodeJava/other/springboot-all/project-second/target/classes/
        //String path = ResourceUtils.getURL("classpath:").getPath();
        MarketStorage marketStorage = storeageService.saveFileAndReturnFileInfo(finalPath, file);
        if (marketStorage == null) {
            return BaseRespVo.invalidParameter("文件保存异常,请稍后重试");
        }
        return BaseRespVo.ok(marketStorage);
    }

}
